<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" media="screen" href="/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/treetable/jquery.treetable.css"/>
    <link rel="stylesheet" href="/css/treetable/jquery.treetable.theme.default.css"/>
    <script src="/js/libs/jquery-2.1.1.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap-select.min.css">
    <script src="/js/bootstrap/bootstrap.min.js"></script>
    <script src="/js/bootstrap/bootstrap-select.min.js"></script>
    <script src="/js/jq.js"></script>
    <script src="/js/plugin/bootstrapvalidator/bootstrapValidator.min.js"></script>
    <script src="/js/common.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/dict.js"></script>
    <script src="/js/libs/jquery.ztree.all-3.5.min.js"></script>
    <script src="/js/my/ztree-menu.js"></script>
    <script src="/js/my/permission.js"></script>
    <script src="/js/plugin/datatables/jquery.dataTables.min.js"></script>
    <script src="/js/plugin/datatables/dataTables.bootstrap.min.js"></script>
    <script src="/js/libs/jquery.treetable.js"></script>
</head>
<body>
<div class="col-xs-12 col-sm-12 col-md-11 col-lg-11">
    <form class="form-horizontal" onsubmit="return false" id="form">
        <fieldset>
            <input type="hidden" id="id" name="id">
            <input type="hidden" id="orderType" name="orderType">
            <div class='form-group'>
                <label class='col-md-2 control-label'>需求人</label>
                <div class='col-md-4'>
                    <input class='form-control' type='hidden' name='originatorId' id='originatorId'>
                    <input style="width: 90%;float: left;" class='form-control' placeholder='需求人' type='text'
                           name='originatorName' id='originatorName'
                           readonly>
                    <button style="width: 10%;float: right; height: 32px; line-height: 32px;"
                            class="layui-btn layui-btn-sm"
                            onclick="showTableAndFlushFields('user', 'user', '用户', false, false, 'originatorId:id', 'originatorName:nickname', 'originatorOfficeId:deptId', 'originatorOfficeName:deptName')">
                        <i class="layui-icon">&#xe615;</i>
                    </button>
                </div>
                <label class='col-md-2 control-label'>需求部门</label>
                <div class='col-md-4'>
                    <input class='form-control' type='hidden' name='originatorOfficeId' id='originatorOfficeId'>
                    <input style="width: 90%;float: left;" class='form-control' placeholder='需求部门' type='text'
                           name='originatorOfficeName' id='originatorOfficeName' readonly>
                    <button style="width: 10%;float: right; height: 32px; line-height: 32px;"
                            class="layui-btn layui-btn-sm"
                            onclick="showSpecialTree('originatorOfficeId', 'originatorOfficeName', 'dept', '部门', 'root', 'select','fasDeptTree', true, true)">
                        <i class="layui-icon">&#xe615;</i>
                    </button>
                </div>
            </div>
            <div class='form-group'>

            </div>
            <div class='form-group'>
                <label class='col-md-2 control-label'>所在公司</label>
                <div class='col-md-4'>
                    <select class="form-control input-sm selectpicker show-tick" name="companyId" id="companyId"
                            title="所属公司" data-live-search="true"></select>
                </div>
                <label class='col-md-2 control-label'>期望交付时间</label>
                <div class='col-md-4'>
                    <input type="text" class="form-control" placeholder="期望交付时间" name="wishPayDate" id="wishPayDate">
                </div>
            </div>
            <div class='form-group'>

            </div>
            <div class='form-group'>
                <label class='col-md-2 control-label'>总价</label>
                <div class='col-md-4'>
                    <input type="text" class="form-control" placeholder="总价" id="totalPrice" name="totalPrice" readonly>
                </div>
                <!--<label class='col-md-2 control-label'>附件</label>-->
                <!--<div class='col-md-4'>-->
                <!--<button type="button" class="layui-btn" id="screenshotPath" name="screenshotPath">-->
                <!--<i class="layui-icon">&#xe67c;</i>上传文件-->
                <!--</button>-->
                <!--</div>-->
            </div>
            <div class='form-group'>
                <label class='col-md-2 control-label'>附件</label>
                <div class="layui-upload col-md-10">
                    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="selectScreenshotPath">
                        选择多文件
                    </button>
                    <input type="hidden" value="" id="screenshotPath" name="screenshotPath">
                    <button type="button" class="layui-btn layui-btn-sm" id="uploadScreenshotPath">开始上传</button>
                    <div class="layui-upload-list">
                        <table class="layui-table">
                            <thead>
                            <tr>
                                <th>文件名</th>
                                <th>大小</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="screenshotPathList"></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">备注</label>
                <div class="col-md-10">
                    <textarea class="form-control" placeholder="备注" name="remark" id="remark"></textarea>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-2 control-label">需求明细</label>
                <div class="col-md-10">
                    <button class="layui-btn layui-btn-normal layui-btn-sm" type="button" onclick="addRow()">
                        <i class="fa fa-address-book"></i> 新增行
                    </button>
                    <button class="layui-btn layui-btn-normal layui-btn-sm" type="button" onclick="delRow()">
                        <i class="fa fa-address-book"></i> 删除行
                    </button>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-11 col-md-offset-1">
                    <table id="dt-table" class="table table-striped table-bordered table-hover" style="width: 100%;">
                        <thead>
                        <tr>
                            <th><input id="selectAllRows" type="checkbox"></th>
                            <th style="width: 50px;">行号</th>
                            <th style="width: 150px;">商品</th>
                            <th style="width: 80px;">供应商</th>
                            <th style="width: 80px;">类型</th>
                            <th style="width: 80px;">交付状态</th>
                            <th style="width: 80px;">规格</th>
                            <th style="width: 50px;">单位</th>
                            <th style="width: 80px;">需求数量</th>
                            <th style="width: 100px;">已交付数量</th>
                            <th style="width: 100px;">待交付数量</th>
                            <th style="width: 100px;">单价</th>
                            <th style="width: 100px;">小计</th>
                        </tr>
                        </thead>
                        <tbody id="orderDetailList">
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="form-actions">
                <div class="row" align="center">
                    <div class="col-md-12">
                        <button class="btn btn-primary" type="submit" onclick="save()">
                            <i class="fa fa-save"></i> 保存
                        </button>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
</div>
<script type="text/javascript">
    $(function () {
        $('#form').bootstrapValidator();
        initData();
        initdetailData();
    });
    layui.use(['layer', 'laydate', 'upload'], function () {
        var layer = layui.layer;
        var laydate = layui.laydate;
        var upload = layui.upload;

        laydate.render({
            elem: '#wishPayDate'
        });

        var screenshotPathListView = $('#screenshotPathList');
        var uploadListIns = upload.render({
            elem: '#selectScreenshotPath'
            , url: '/files'
            , accept: 'file'
            , multiple: true
            , auto: false
            , bindAction: '#uploadScreenshotPath'
            , choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // 重新获得所有上传文件
                        $('#screenshotPath').val('');
                        $('.screenshotPathFile').each(function () {
                            $('#screenshotPath').val($('#screenshotPath').val() + '|' + $(this).data('id'));
                        });
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    screenshotPathListView.append(tr);
                });
            }
            , done: function (res, index, upload) {
                if (res.code === 0) { //上传成功
                    var tr = screenshotPathListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(0).html('<a target="_blank" data-id="' + res.data.id + '" class="screenshotPathFile" href="/files' + res.data.url + '">' + res.data.fileName + '</a>');
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    // tds.eq(3).html(''); //清空操作

                    // 追加文件id
                    $('#screenshotPath').val($('#screenshotPath').val() + '|' + res.data.id);
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            , error: function (index, upload) {
                var tr = screenshotPathListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });
    });

    layui.use(['layer', 'laydate'], function () {
        var layer = layui.layer;
    });
    var companys = showDictSelect('companyId', 'company', '', 'beep');
    var example = $('#dt-table').DataTable({
        "columnDefs": [
            {
                targets: 1,
                width: "100px"
            }
        ],
        "ordering": false,
        // "displayLength" : 10,
        // "scrollY": "calc(100vh - 150px)",
        "scrollX": true,
        "searching": false,
        "processing": true,
        "language": {
            "url": "/js/plugin/datatables/Chinese.lang"
        },
        "dom": "<'dt-toolbar'r>t<'dt-toolbar-footer'<'col-sm-4 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-8' p v>>",
        "createdRow": function (row, data, index) {

        }
    });



    function initData() {
        var id = getUrlParam("id");
        if (id != "") {
            $.ajax({
                type: 'get',
                url: '/order/' + id,
                async: false,
                success: function (json) {
                    if (json.code === 0) {
                        var data = json.data;
                        $('#id').val(data.id);
                        $('#orderType').val(data.orderType)
                        $('#originatorId').val(data.originatorId);
                        $('#originatorName').val(data.originatorName);
                        $('#originatorOfficeId').val(data.originatorOfficeId);
                        $('#originatorOfficeName').val(data.originatorOfficeName);
                        $('#companyId').val(data.companyId);
                        $('#wishPayDate').val(data.wishPayDate);
                        $('#totalPrice').val(data.totalPrice);
                        $('#remark').val(data.remark);
                        $('#screenshotPath').val(data.screenshotPath);
                        var screenshotPaths = data.screenshotPaths;
                        if (screenshotPaths) {
                            $.each(screenshotPaths, function (index, file) {
                                var tr = $(['<tr id="upload-' + index + '">'
                                    , '<td>'
                                    , '<a target="_blank" data-id="' + file.id + '" class="screenshotPathFile" href="/files' + file.url + '">' + file.fileName + '</a>'
                                    , '</td>'
                                    , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                                    , '<td>已上传</td>'
                                    , '<td>'
                                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                                    , '</td>'
                                    , '</tr>'].join(''));

                                //单个重传
                                tr.find('.demo-reload').on('click', function () {
                                    obj.upload(index, file);
                                });

                                //删除
                                tr.find('.demo-delete').on('click', function () {
                                    // delete files[index]; //删除对应的文件
                                    tr.remove();
                                    // 重新获得所有上传文件
                                    $('#screenshotPath').val('');
                                    $('.screenshotPathFile').each(function () {
                                        $('#screenshotPath').val($('#screenshotPath').val() + '|' + $(this).data('id'));
                                    });
                                });

                                $('#screenshotPathList').append(tr);
                            });
                        }
                    }
                }
            });
        }
    }

    function initdetailData() {
        var orderId = getUrlParam("id");
        var index = document.getElementsByTagName("td").length;
        if (orderId != "") {
            $.ajax({
                type: 'get',
                url: '/orderDetail/getByParentId/' + orderId,
                async: false,
                success: function (json) {
                    if (json.code === 0) {
                        var data = json.data;

                        for (var i = 0; i < data.length; i++) {//遍历行
                            $('#' + i + '_id').val(data[i].id);
                            $('#' + i + '_goodsId').val(data[i].goodsId);
                            $('#' + i + '_goodsName').val(data[i].goodsName);
                            $('#' + i + '_supplierId').val(data[i].supplierId);
                            $('#' + i + '_supplierName').val(data[i].supplierName);
                            $('#' + i + '_demandType').val(data[i].demandType);
                            $('#' + i + '_orderDetailType').val(data[i].orderDetailType);
                            $('#' + i + '_detailSpec').val(data[i].detailSpec);
                            $('#' + i + '_detailUnit').val(data[i].detailUnit);
                            $('#' + i + '_detailNum').val(data[i].detailNum);
                            $('#' + i + '_actNum').val(data[i].actNum);
                            $('#' + i + '_waitNum').val(data[i].waitNum);
                            $('#' + i + '_detailSinprice').val(data[i].detailSinprice);
                            $('#' + i + '_detailTotalPrice').val(data[i].detailTotalPrice);

                            if (i < data.length - 1) {
                                addRow();
                            }
                        }
                    }
                }
            });
        }
    }

    function initDetail(rownum, id) {
        $.ajax({
            type: 'get',
            url: '/goods/' + id,
            success: function (json) {
                if (json.code === 0) {
                    var data = json.data;
                    var row = $('#row_' + rownum).parent();
                    $('#' + rownum + '_detailSpec').val(data.specification);
                    $('#' + rownum + '_detailUnit').val(data.unit);
                    $('#' + rownum + '_detailNum').val(0);
                    $('#' + rownum + '_actNum').val(0);
                    $('#' + rownum + '_waitNum').val(0);
                    $('#' + rownum + '_detailSinprice').val(data.unitPrice);
                    $('#' + rownum + '_detailTotalPrice').val(data.unitPrice);

                }
            },
            error: function (xhr, textStatus, errorThrown) {
                var msg = xhr.responseText;
                var response = JSON.parse(msg);
            }

        })

    }

    var rownum = 0;

    function addRow() {
        var elementGoods = rownum + "_goods";
        var elementGoodsId = elementGoods + 'Id';
        var elementGoodsName = elementGoods + 'Name';
        var elementSupplier = rownum + "_supplier";
        var elementSupplierId = elementSupplier + 'Id';
        var elementSupplierName = elementSupplier + 'Name';
        example.row.add([
            "<input id='row_" + rownum + "' name='selectRow' data-detailId='' type='checkbox' >",
            (rownum + 1),
            "<div style='width: 150px;'><input class='form-control' type='hidden' name='orderDetailList[" + rownum + "].goodsId' id='" + elementGoodsId + "'>" +
            "<input style='width: 100px;float: left;'class='form-control' placeholder='商品' " +
            "type='text' name='orderDetailList[" + rownum + "].goodsName' id='" + elementGoodsName + "' readonly>" +
            "<button style='width: 50px;float: right; height: 32px; line-height: 32px;' class='layui-btn layui-btn-sm'" +
            "onclick=\"showTableAndFlushRow('" + elementGoods + "','fas/goods','goods', '商品')\">" +
            "<i class='layui-icon'>&#xe615;</i>" +
            "</button></div>",
            "<div style='width: 150px;'><input class='form-control' type='hidden' name='orderDetailList[" + rownum + "].supplierId' id='" + elementSupplierId + "'>" +
            "<input style='width: 100px;float: left;'class='form-control' placeholder='供应商' " +
            "type='text' name='orderDetailList[" + rownum + "].supplierName' id='" + elementSupplierName + "' readonly>" +
            "<button style='width: 50px;float: right; height: 32px; line-height: 32px;' class='layui-btn layui-btn-sm'" +
            "onclick=\"showTableAndFlushFields('fas/supplier','supplier', '供应商', true, false,'" + elementSupplierId + ":id', '" + elementSupplierName + ":name')\">" +
            "<i class='layui-icon'>&#xe615;</i>" +
            "</button></div>",
            "<select class='form-control input-sm' name='orderDetailList[" + rownum + "].demandType' id='" + rownum + "_demandType' " +
            "title='类型' ></select>",
            "<select class='form-control input-sm' name='orderDetailList[" + rownum + "].orderDetailType' id='" + rownum + "_orderDetailType' " +
            "title='交付状态' disabled=\"disabled\"></select>",
            "<input class='form-control input-sm' id='" + rownum + "_detailSpec' name='orderDetailList[" + rownum + "].detailSpec' readonly>" +
            "<input type='hidden' id='" + rownum + "_id' name='orderDetailList[" + rownum + "].id' readonly>",
            "<input class='form-control input-sm' id='" + rownum + "_detailUnit' name='orderDetailList[" + rownum + "].detailUnit' readonly>",
            "<input class='form-control input-sm' onkeyup =\"amounta(this)\" id='" + rownum + "_detailNum' name='orderDetailList[" + rownum + "].detailNum'>",
            "<input class='form-control' id='" + rownum + "_actNum' name='orderDetailList[" + rownum + "].actNum' readonly>",
            "<input class='form-control' id='" + rownum + "_waitNum' name='orderDetailList[" + rownum + "].waitNum' readonly>",
            "<input class='form-control' onkeyup =\"amounta(this)\" id='" + rownum + "_detailSinprice' name='orderDetailList[" + rownum + "].detailSinprice'>",
            "<input class='form-control' id='" + rownum + "_detailTotalPrice' name='orderDetailList[" + rownum + "].detailTotalPrice' readonly>"
        ]).draw();
        showDictSelect(rownum + '_companyId', 'company', '', 'beep');
        showDictSelect(rownum + '_demandType', 'demand_Type', '', '10');
        showDictSelect(rownum + '_orderDetailType', 'detail_status', '', '0');
        //给第一个单元格的checkbox绑定点击事件
        $('#row_' + rownum).bind('click', function () {
            var $row = $(this).parent().parent();
            if ($row.hasClass('success')) {
                $row.removeClass('success');
            } else {
                $row.addClass('success');
            }
        });

        rownum++;
    }

    addRow();

    function delRow() {
        example.rows('.success').remove().draw(false);
        countMoney();
    }

    function amounta(obj) {
        var id = $(obj).attr('id');
        var idp = id.split('_')[0];
        var num = $('#' + idp + '_detailNum').val();	//明细数量
        num = Number(num);
        var price = $('#' + idp + '_detailSinprice').val();	//明细单价
        price = parseFloat(price);
        var totalPrice = price * num;
        if (isNaN(totalPrice)) {
            totalPrice = 0;
        }
        $('#' + idp + '_detailTotalPrice').val(totalPrice);	//明细小计
        countMoney();
    }

    function countMoney() {
        var amount = 0.0; //采购总额
        var trs = $('#orderDetailList').find('tr');
        $(trs).each(function (i, o) {
            var idp = $($(this).find('input[type=checkbox]')[0]).attr('id');
            idp = idp.split('_')[1]
            var title = $(this).find('i.fa fa-address-book').attr('title');
            if (title == '撤销删除') {
                return true;
            }
            //计算应收的金额
            var a = $('#' + idp + '_detailTotalPrice').val();
            if (isNaN(a)) {
                a = 0;
            }
            a = parseFloat(a);
            amount += a;
        });
        if (isNaN(amount)) {
            amount = 0;
        }
        var a = $('#totalPrice').val(amount);
    }

    // layui.use('upload', function () {
    //     var upload = layui.upload;
    //     upload.render({
    //         elem: '#screenshotPath' //绑定元素
    //         , accept: 'file' //允许上传的文件类型
    //         , url: '/files' //上传接口
    //         , done: function (res, index, upload) {
    //             layer.msg("上传成功");
    //         }
    //     });
    // });

    function save() {
        $('#form').bootstrapValidator();
        var bootstrapValidator = $("#form").data('bootstrapValidator');
        bootstrapValidator.validate();
        if (!bootstrapValidator.isValid()) {
            return;
        }

        var formdata = $("#form").serializeObject();
        var orderType = formdata['orderType'];
        if (orderType == '0') {
            $.ajax({
                type: 'put',
                url: '/order',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(formdata),
                success: function (data) {
                    if (data.code === 0) {
                        layer.msg("修改成功", {shift: -1, time: 1000}, function () {
                            parent.location.reload();
                        });
                    } else {
                        layer.msg("只能由创建人修改", {shift: -1, time: 1000}, function () {
                        });
                    }

                }
            });
        } else {
            layer.msg("已提交后需求单不可修改", {shift: -1, time: 1000});
        }
    }

</script>
</body>
</html>
